import React, { Component } from "react";

import {
  Button,
  ButtonToolbar,
  Panel,
  Grid,
  Row,
  Col,
  Input,
  Icon,
  Table,
  Modal,
  Form,
  SelectPicker,
  Schema,
  Alert,
} from "rsuite";

import moment from "moment";
import CustomField from "../../../components/form/customField";
import http from "../../../components/http/http";
import rest from "../../../assets/config/rest.json";

class User extends Component {
  constructor(props) {
    super(props);
    this.state = {
      title: "User",
      showModal: false,
      showPassword: true,
      disableLoginId: true,
      roles: [],
      table: {
        name: "",
        pageNum: 1,
        pageSize: 10,
        total: 0,
        data: [],
      },
      checkModel: this.checkModel(),
      tableLoading: false,
      currentPermits: [],
      form: {
        id: "",
        loginId: "",
        password: "",
        confirmPassword: "",
        roleId: "",
        name: "",
        email: "",
        telephone: "",
      },
    };
    this.loadRoles = this.loadRoles.bind(this);
    this.loadUsers = this.loadUsers.bind(this);
    this.handleChangePage = this.handleChangePage.bind(this);
    this.handleChangeLength = this.handleChangeLength.bind(this);
    this.newUser = this.newUser.bind(this);
    this.editUser = this.editUser.bind(this);
    this.deleteUser = this.deleteUser.bind(this);
    this.submitUser = this.submitUser.bind(this);
  }

  UNSAFE_componentWillMount() {
    let menus = localStorage.getItem(rest.menu);
    if (!!menus) {
      this.setState({
        currentPermits: JSON.parse(menus)
          .filter((x) => x.name === "System")[0]
          .children.filter((y) => y.name === "User")[0].permits,
      });
    }
    this.loadRoles();
    this.loadUsers();
  }

  componentDidMount() {}

  componentWillUnmount() {
    this.setState = (state, callback) => {
      return;
    };
  }

  loadRoles() {
    http.get(rest.roles).then((response) => {
      if (response.status === 200) {
        this.setState({ roles: response.data });
      }
    });
  }

  loadUsers() {
    const { table } = this.state;
    this.setState({ tableLoading: true });
    http
      .get(rest.users, {
        params: {
          name: table.name,
          pageNum: table.pageNum,
          pageSize: table.pageSize,
        },
      })
      .then((response) => {
        if (response.status === 200) {
          let result = response.data.result.map((x) => {
            x.role = x.roleVo.code;
            x.createTime = moment(x.createTime).format("YYYY-MM-DD HH:mm:ss");
            x.status = !!x.status ? "正常" : "停用";
            return x;
          });
          this.setState({
            tableLoading: false,
            table: {
              ...table,
              data: result,
              total: response.data.total,
            },
          });
        }
      });
  }

  handleChangePage(e) {
    const { table } = this.state;
    this.setState(
      {
        table: {
          ...table,
          pageNum: e,
        },
      },
      () => {
        this.loadUsers();
      }
    );
  }

  handleChangeLength(e) {
    const { table } = this.state;
    this.setState(
      {
        table: {
          ...table,
          pageSize: e,
        },
      },
      () => {
        this.loadUsers();
      }
    );
  }

  newUser() {
    this.setState({
      showPassword: true,
      showModal: true,
      disableLoginId: false,
      form: {
        id: "",
        loginId: "",
        password: "",
        confirmPassword: "",
        roleId: "",
        name: "",
        email: "",
        telephone: "",
      },
    });
  }

  editUser(rowData) {
    this.setState({
      showPassword: false,
      showModal: true,
      disableLoginId: true,
      form: {
        id: rowData.id,
        loginId: rowData.loginId,
        password: "only for edit, useless",
        confirmPassword: "only for edit, useless",
        roleId: Number(rowData.roleVo.id),
        name: rowData.name,
        email: rowData.email,
        telephone: rowData.telephone,
      },
    });
  }

  deleteUser(id) {
    http.delete(`${rest.user}/${id}`).then((response) => {
      if (response.status === 200) {
        Alert.success("操作成功!");
        this.setState({ showModal: false });
        this.loadUsers();
      } else {
        Alert.error("操作失败!");
      }
    });
  }

  submitUser() {
    const { form } = this.state;
    const { userForm } = this.refs;
    let callback = (response) => {
      if (response.status === 200) {
        Alert.success("操作成功!");
        this.setState({ showModal: false });
        this.loadUsers();
      } else {
        Alert.error("操作失败!");
      }
    };
    userForm.checkAsync().then((result) => {
      if (result.hasError) {
        return;
      }
      if (!!form.id) {
        http
          .put(rest.user, {
            id: form.id,
            name: form.name,
            telephone: form.telephone,
            email: form.email,
            roleId: form.roleId,
          })
          .then(callback);
      } else {
        http
          .post(rest.user, {
            loginId: form.loginId,
            password: window.btoa(form.password),
            name: form.name,
            telephone: form.telephone,
            email: form.email,
            roleId: form.roleId,
          })
          .then(callback);
      }
    });
  }

  checkModel() {
    const { StringType, NumberType } = Schema.Types;
    let confirmPasswordRule = (value, data) => {
      return value === data.password;
    };
    let telephoneRule = (value, data) => {
      let teleReg = /^((0\d{2,3})-)(\d{7,8})$/;
      let mobileReg = /^1[358]\d{9}$/;
      return !(!teleReg.test(value) && !mobileReg.test(value));
    };
    return Schema.Model({
      loginId: StringType().isRequired("This field is required."),
      password: StringType().isRequired("This field is required."),
      confirmPassword: StringType()
        .addRule(
          confirmPasswordRule,
          "Confirm password is not equal to password"
        )
        .isRequired("This field is required."),
      roleId: NumberType().isRequired("This field is required."),
      name: StringType().isRequired("This field is required."),
      email: StringType()
        .isEmail("Please enter a valid email address.")
        .isRequired("This field is required."),
      telephone: StringType()
        .addRule(telephoneRule, "Please check your telephone format")
        .isRequired("This field is required."),
    });
  }

  render() {
    const {
      title,
      showModal,
      roles,
      table,
      tableLoading,
      form,
      checkModel,
      showPassword,
      disableLoginId,
      currentPermits,
    } = this.state;
    return (
      <Grid fluid>
        <Panel header={title}>
          <Panel
            header={<Icon icon="search"> 查询条件</Icon>}
            style={{ background: "#fff" }}
            collapsible
            bordered
            defaultExpanded
          >
            <Row>
              <Col xs={4}>
                <Input
                  placeholder="请输入用户名"
                  value={table.name}
                  onChange={(e) => {
                    this.setState({
                      table: {
                        ...table,
                        name: e,
                      },
                    });
                  }}
                />
              </Col>
              <Col>
                <ButtonToolbar>
                  <Button color="blue" onClick={this.loadUsers}>
                    <Icon icon="search-peoples" /> 查询
                  </Button>
                  <Button
                    color="orange"
                    onClick={() => {
                      this.setState(
                        {
                          table: {
                            ...table,
                            name: "",
                          },
                        },
                        () => {
                          this.loadUsers();
                        }
                      );
                    }}
                  >
                    <Icon icon="reload" /> 重置
                  </Button>
                  {currentPermits.indexOf("system:user:c") !== -1 ? (
                    <Button color="green" onClick={this.newUser}>
                      <Icon icon="plus" /> 新建
                    </Button>
                  ) : null}
                </ButtonToolbar>
              </Col>
            </Row>
          </Panel>
          <Panel
            header="用户列表"
            style={{ marginTop: "1rem", background: "#fff" }}
            bordered
          >
            <Row>
              <Col>
                <Table
                  loading={tableLoading}
                  autoHeight={true}
                  data={table.data}
                >
                  <Table.Column flexGrow={1}>
                    <Table.HeaderCell>登录号</Table.HeaderCell>
                    <Table.Cell dataKey="loginId" />
                  </Table.Column>

                  <Table.Column flexGrow={1}>
                    <Table.HeaderCell>姓名</Table.HeaderCell>
                    <Table.Cell dataKey="name" />
                  </Table.Column>

                  <Table.Column flexGrow={1}>
                    <Table.HeaderCell>角色</Table.HeaderCell>
                    <Table.Cell dataKey="role" />
                  </Table.Column>

                  <Table.Column flexGrow={1}>
                    <Table.HeaderCell>电话号码</Table.HeaderCell>
                    <Table.Cell dataKey="telephone" />
                  </Table.Column>

                  <Table.Column flexGrow={1}>
                    <Table.HeaderCell>电子邮箱</Table.HeaderCell>
                    <Table.Cell dataKey="email" />
                  </Table.Column>

                  <Table.Column flexGrow={1}>
                    <Table.HeaderCell>创建时间</Table.HeaderCell>
                    <Table.Cell dataKey="createTime" />
                  </Table.Column>

                  <Table.Column flexGrow={1}>
                    <Table.HeaderCell>状态</Table.HeaderCell>
                    <Table.Cell dataKey="status" />
                  </Table.Column>
                  <Table.Column flexGrow={1}>
                    <Table.HeaderCell>操作</Table.HeaderCell>
                    <Table.Cell>
                      {(rowData) => {
                        return (
                          <ButtonToolbar>
                            {currentPermits.indexOf("system:user:u") !== -1 ? (
                              <Button
                                color="blue"
                                size="xs"
                                onClick={() => {
                                  this.editUser(rowData);
                                }}
                              >
                                <Icon icon="edit" /> 编辑
                              </Button>
                            ) : null}

                            {currentPermits.indexOf("system:user:d") !== -1 ? (
                              <Button
                                color="red"
                                size="xs"
                                onClick={() => {
                                  this.deleteUser(rowData.id);
                                }}
                              >
                                <Icon icon="trash2" /> 删除
                              </Button>
                            ) : null}
                          </ButtonToolbar>
                        );
                      }}
                    </Table.Cell>
                  </Table.Column>
                </Table>
                <Table.Pagination
                  lengthMenu={[
                    {
                      value: 10,
                      label: 10,
                    },
                    {
                      value: 20,
                      label: 20,
                    },
                  ]}
                  activePage={table.pageNum}
                  displayLength={table.pageSize}
                  total={table.total}
                  onChangePage={this.handleChangePage}
                  onChangeLength={this.handleChangeLength}
                />
              </Col>
            </Row>
          </Panel>
        </Panel>
        <Modal
          size="sm"
          show={showModal}
          onHide={() => {
            this.setState({ showModal: false });
          }}
        >
          <Modal.Header>
            <Modal.Title>新增/编辑用户</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <Form
              fluid
              ref="userForm"
              onChange={(form) => {
                this.setState({ form: form });
              }}
              formValue={form}
              model={checkModel}
            >
              <CustomField
                disabled={disableLoginId}
                name="loginId"
                label="登录名:"
                accepter={Input}
                placeholder="请输入登录名"
                type="text"
              />
              <CustomField
                style={{ display: showPassword ? "block" : "none" }}
                name="password"
                label="密码:"
                accepter={Input}
                placeholder="请输入密码"
                type="password"
              />
              <CustomField
                style={{ display: showPassword ? "block" : "none" }}
                name="confirmPassword"
                label="确认密码:"
                accepter={Input}
                placeholder="请输入确认密码"
                type="password"
              />
              <CustomField
                name="roleId"
                label="角色:"
                accepter={SelectPicker}
                placeholder="请选择角色"
                block={true}
                searchable={false}
                data={roles}
                valueKey="id"
                labelKey="code"
              />
              <CustomField
                name="name"
                label="姓名:"
                accepter={Input}
                placeholder="请输入姓名"
                type="text"
              />
              <CustomField
                name="email"
                label="电子邮件:"
                accepter={Input}
                placeholder="请输入电子邮件"
                type="text"
              />
              <CustomField
                name="telephone"
                label="电话号码:"
                accepter={Input}
                placeholder="请输入电话号码"
                type="text"
              />
            </Form>
          </Modal.Body>
          <Modal.Footer>
            <Button onClick={this.submitUser} appearance="primary">
              确认
            </Button>
            <Button
              onClick={() => {
                this.setState({ showModal: false });
              }}
              appearance="subtle"
            >
              取消
            </Button>
          </Modal.Footer>
        </Modal>
      </Grid>
    );
  }
}

export default (props) => <User {...props} key={props.location.pathname} />;
